<?php
// $Id$
$config_dir =  dirname(dirname(dirname(__FILE__))) . "/config/";
require_once( $config_dir . "config.controller.inc.php");
/**
 * Controller_Brand 控制器
 */
class Controller_Brand extends Controller_Abstract
{

	function actionIndex()
	{
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
	}
    
    function actionNewBrand()
    {
        $form = new Form_NewBrand(url('brand/newbrand'));
        if ( $this->_context->isPOST() && $form->validate($_POST) )
        {
            try
            {
                $brand = new Brand($form->values());
                $values = $form->values();
                $brand->brand_name = $values["brand_name"];
                $brand_querry = Brand::find("brand_name = ?", $brand->brand_name)->getOne();
                $category_querry = GoodsCategory::find("category_id = ?", $values["brand_category"])->getOne();
                if ( $brand_querry != null && $brand_querry->brand_id != null )
                {
                    $ret = array();
                    $ret["answer"] = "new_brand";
                    $ret["ret_code"] = -1;
                    $ret["info"] = "New brand failed, brand exist.";
                    $ret["data"] = "";
                    $callback = $values["callback"];
                    echo $callback .  "(" . json_encode($ret) . ")";
                    exit();
                }
                else if ( $category_querry != null && $category_querry->category_id != null )
                {
                    $time_now = gettimeofday();
                    $brand->brand_url = $values["brand_url"];
                    $brand->category_id = $category_querry->category_id;
                    $brand->brand_id  = ($time_now["sec"] + "") . $time_now["usec"];
                    $brand->save(99,'create');
                    
                    $ret = array();
                    $ret["answer"] = "new_brand";
                    $ret["ret_code"] = 1;
                    $ret["info"] = "";
                    $ret["data"] = "";
                    $callback = $values["callback"];
                    echo $callback .  "(" . json_encode($ret) . ")";
                    exit();
                }
            }
            catch (Exception $ex)
            {
                print_r($ex);
                exit();
            }
        }
    }
    
    function actionExportBrandGoodsXLS()
    {
        $form = new Form_ExportBrandGoodsXLS(url('brand/exportbrandgoodsxls'));
        if ( $this->_context->isPOST() && $form->validate($_POST) )
        {
            try
            {
                set_include_path(PEAR_INCLUDE_PATH);
                require_once(SPREADSHEET_INCLUDE_PATH . "Excel/Writer.php");
                $values = $form->values();
                
                $xls_item_list = $values["xls_item_list"];
                $category_id = $values["category_id"];
                $brand_id = $values["brand_id"];
                $brand_name = $values["brand_name"];
                $json_path = JSON_EXPORT_XLS_PATH . $category_id . "/" . $brand_id . ".js";
                
                $fp = fopen($json_path,'rb');
                if ($fp == null)
                {
                    exit();
                }
                $json_string = fread($fp, 5000000);
                $json_string = substr($json_string, strlen("fillTable("));
                $json_string = substr($json_string, 0, strlen($json_string)-strlen(", 'console/brand_goods');"));
                fclose($fp);
                $json_data = json_decode($json_string);
                //print_r($json_data);
                
                // Creating a workbook
                $workbook = new Spreadsheet_Excel_Writer();

                // sending HTTP headers
                //$title = iconv('utf-8//IGNORE', 'gbk', $brand_name);
                $title = $brand_name;
                $workbook->send($title . '.xls');

                $format = &$workbook->addFormat();
                $format->setBold();
                $format->setFgColor('white');
                $format->setPattern(1);

                // Creating a worksheet
                $worksheet =& $workbook->addWorksheet($title);
                //$worksheet->setInputEncoding('gbk'); 
                ///*
                $worksheet->write(0, 0, iconv('utf-8//IGNORE', 'gbk', '商品ID'), $format);
                $worksheet->write(0, 1, iconv('utf-8//IGNORE', 'gbk', '在架商品ID'), $format);
                $worksheet->write(0, 2, iconv('utf-8//IGNORE', 'gbk', '商品名'), $format);
                $worksheet->write(0, 3, iconv('utf-8//IGNORE', 'gbk', '大图链接'), $format);
                $worksheet->write(0, 4, iconv('utf-8//IGNORE', 'gbk', '中图链接'), $format);
                $worksheet->write(0, 5, iconv('utf-8//IGNORE', 'gbk', '小图链接'), $format);
                $worksheet->write(0, 6, iconv('utf-8//IGNORE', 'gbk', '市场价'), $format);
                $worksheet->write(0, 7, iconv('utf-8//IGNORE', 'gbk', '商城价'), $format);
                $worksheet->write(0, 8, iconv('utf-8//IGNORE', 'gbk', '会员价'), $format);
                $worksheet->write(0, 9, iconv('utf-8//IGNORE', 'gbk', '库存'), $format); 
                //*/
                
                /*
                $worksheet->write(0, 0, '商品ID', $format);
                $worksheet->write(0, 1, '在架商品ID', $format);
                $worksheet->write(0, 2, '商品名', $format);
                $worksheet->write(0, 3, '大图链接', $format);
                $worksheet->write(0, 4, '中图链接', $format);
                $worksheet->write(0, 5, '小图链接', $format);
                $worksheet->write(0, 6, '市场价', $format);
                $worksheet->write(0, 7, '商城价', $format);
                $worksheet->write(0, 8, '会员价', $format);
                $worksheet->write(0, 9, '库存', $format);
                //*/
                
                $i = 1;
                $item_list = explode("|", $xls_item_list);
                $items = $json_data->goods;
                
                foreach( $item_list as $item_key )
                {
                
                    $item = $items[$item_key];
                    /*
                    $worksheet->write($i, 0, $item->goods_id, $format);
                    $worksheet->write($i, 1, $item->goods_onshelf_id, $format);
                    $worksheet->write($i, 2, $item->goods_name, $format);
                    $worksheet->write($i, 3, $item->big_img_urls, $format);
                    $worksheet->write($i, 4, $item->img_urls, $format);
                    $worksheet->write($i, 5, $item->small_img_urls, $format);
                    $worksheet->write($i, 6, $item->market_price, $format);
                    $worksheet->write($i, 7, $item->mall_price, $format);
                    $worksheet->write($i, 8, $item->vip_price, $format);
                    $worksheet->write($i, 9, $item->stock, $format);
                    //*/
                    
                    $worksheet->write($i, 0, iconv('utf-8//IGNORE', 'gbk', "'" . $item->goods_id), $format);
                    $worksheet->write($i, 1, iconv('utf-8//IGNORE', 'gbk', "'" . $item->goods_onshelf_id), $format);
                    $worksheet->write($i, 2, iconv('utf-8//IGNORE', 'gbk', $item->goods_name), $format);
                    $worksheet->write($i, 3, iconv('utf-8//IGNORE', 'gbk', $item->big_img_urls), $format);
                    $worksheet->write($i, 4, iconv('utf-8//IGNORE', 'gbk', $item->img_urls), $format);
                    $worksheet->write($i, 5, iconv('utf-8//IGNORE', 'gbk', $item->small_img_urls  	), $format);
                    $worksheet->write($i, 6, iconv('utf-8//IGNORE', 'gbk', $item->market_price), $format);
                    $worksheet->write($i, 7, iconv('utf-8//IGNORE', 'gbk', $item->mall_price), $format);
                    $worksheet->write($i, 8, iconv('utf-8//IGNORE', 'gbk', $item->vip_price), $format);
                    $worksheet->write($i, 9, iconv('utf-8//IGNORE', 'gbk', $item->stock), $format);
                    /*
                    echo $item->goods_id;echo "<br/>";
                    echo $item->goods_onshelf_id;echo "<br/>";
                    echo $item->goods_name;echo "<br/>";
                    echo $item->big_img_urls;echo "<br/>";
                    echo $item->img_urls;echo "<br/>";
                    echo $item->small_img_urls;echo "<br/>";
                    echo $item->market_price;echo "<br/>";
                    echo $item->mall_price;echo "<br/>";
                    echo $item->vip_price;echo "<br/>";
                    echo $item->stock;echo "<br/>";
                    */
                    
                    ++$i;
                }
                $workbook->close();
            }
            catch (Exception $ex)
            {
                print_r($ex);
                exit();
            }
        }
    }
    
    function actionGenerateBrandGoodsJSON()
    {
        $form = new Form_GenerateBrandGoodsJSON(url('brand/generatebrandgoodsjson'));
        if ( $this->_context->isPOST() && $form->validate($_POST) )
        {
            try
            {
                $values = $form->values();
                
                $goods_brand_item = Brand::find("brand_id = ?", $values["brand_id"])->getOne();
                $goods_brand = Array();
                $goods_brand["brand_name"] = $goods_brand_item->brand_name;
                
                $brand_goods = Array();
                $goods_index = 0;
                $goods_info_list = GoodsInfo::find("brand_id = ?", $values["brand_id"])->getAll();
                while ( $goods_info_list->current() )
                {
                    $goods_info_item = $goods_info_list->current();
                    $goods_property = GoodsProperty::find("property_id = ?",$goods_info_item->property_id)->getOne();
                    $goods_onshelf_list = GoodsOnshelf::find("goods_id = ?",$goods_info_item->goods_id)->getAll();
                    while ( $goods_onshelf_list->current() )
                    {
                        $goods_onshelf_item = $goods_onshelf_list->current();

                        $brand_goods[$goods_index]["goods_id"] = $goods_info_item->goods_id;
                        $brand_goods[$goods_index]["goods_name"] = $goods_info_item->goods_name;
                        //$brand_goods[$goods_index]["goods_no"] = $goods_info_item->goods_no;
                        $brand_goods[$goods_index]["small_img_urls"] = $goods_info_item->small_img_urls;
                        $brand_goods[$goods_index]["img_urls"] = $goods_info_item->img_urls;
                        $brand_goods[$goods_index]["big_img_urls"] = $goods_info_item->big_img_urls;
                        
                        $brand_goods[$goods_index]["goods_onshelf_id"] = $goods_onshelf_item->goods_onshelf_id;
                        $brand_goods[$goods_index]["stock"] = $goods_onshelf_item->stock;
                        $brand_goods[$goods_index]["market_price"] = $goods_onshelf_item->market_price;
                        $brand_goods[$goods_index]["mall_price"] = $goods_onshelf_item->mall_price;
                        $brand_goods[$goods_index]["vip_price"] = $goods_onshelf_item->vip_price;
                        
                        ++$goods_index;
                        $goods_onshelf_list->next();
                    }
                    $goods_info_list->next();
                }
                
                $brand_json = Array();
                $brand_json["brand"] = $goods_brand;
                $brand_json["goods"] = $brand_goods;
                
                $json_path = JSON_EXPORT_XLS_PATH . $goods_brand_item->category_id . "/";
                if ($json_path != '.' && $json_path != '..' && !is_dir($json_path))
                {
                    passthru("mkdir -p $json_path >/dev/null");
                }
                
                $json_name = $json_path. $goods_brand_item->brand_id . ".js";
                $json = "fillTable(" . json_encode($brand_json) . ", 'console/brand_goods');";
                $fh = fopen($json_name, "w");
                if ( $fh == null )
                {
                    //echo $callback .  "(" . $json . ")";
                    exit();
                }
                fwrite($fh, $json);
                fclose($fh);
            }
            catch (Exception $ex)
            {
                print_r($ex);
                exit();
            }
        }
    }
    
    function actionGenerateBrandTree()
    {
        try
        {
            $brand_array = Brand::find("brand_id is not null")->getAll();
            $brand_tree  = Array();
            while ( $brand_array->current() )
            {
                $brand_item = $brand_array->current();
               
                if ($brand_tree[$brand_item->category_id])
                {
                    $brand_index = count($brand_tree[$brand_item->category_id]);
                }
                else
                {
                    $brand_index = 0;
                }
                
                //$brand_index = count($brand_tree[$brand_item->category_id]);
                $brand_tree[$brand_item->category_id][$brand_index]["brandName"] = $brand_item->brand_name;
                $brand_tree[$brand_item->category_id][$brand_index]["brandId"] = $brand_item->brand_id;
                $brand_array->next();
            }
            $json = "fillAct(" . json_encode($brand_tree) . ", 'public/brand_tree');";
            $fh = fopen(JSON_BRAND_TREE_PATH, "w");
            if ( $fh == null )
            {
                //echo $callback .  "(" . $json . ")";
                exit();
            }
            fwrite($fh, $json);
            fclose($fh);
            
            /*
            $brand_json = Array();
            foreach ( $brand_tree as $category_id=>$brands )
            {
                $category_name = GoodsCategory::find("category_id = ?", $category_id)->getOne()->category_name;
                if ( $category_name != null )
                {
                    $brand_json[$category_name] = $brands;
                }
            }
            
            echo json_encode($brand_json);
            */
        }
        catch (Exception $ex)
        {
            print_r($ex);
            exit();
        }
    }

    
    function actionGenerateBrandGoodsRecommendedJSON()
    {
        $form = new Form_GenerateBrandGoodsJSON(url('category/generatecategorygoodsjson'));
        if ( $this->_context->isPOST() && $form->validate($_POST) )
        {
            try
            {
                if ( $_FILES["goods_file_xls"]["error"] > 0 )
                {
                    echo "error: " . $_FILES["goods_file_xls"]["error"] . "<br />";
                    exit();
                }
                else if ($_FILES["goods_file_xls"]["type"] != "application/vnd.ms-excel")
                {
                    echo $_FILES["goods_file_xls"]["name"] . "is not a excel file.<br />";
                    exit();
                }
                else
                {
                    $time_now = gettimeofday();
                    $time_now_version = $time_now["sec"] . $time_now["usec"];
                    $xls_file = XLS_UPLOAD_GOODS_PATH . $time_now["sec"] . $time_now["usec"] . $_FILES["goods_file_xls"]["name"];
                    if (file_exists($xls_file))
                    {
                        echo $_FILES["goods_file_xls"]["name"] . " already exists. ";
                        exit();
                    }
                    else
                    {
                        move_uploaded_file($_FILES["goods_file_xls"]["tmp_name"], $xls_file);
                        $xls_data = new Spreadsheet_Excel_Reader();
                        $xls_data->setOutputEncoding("UTF-8");
                        $xls_data->read($xls_file);
                        $json_goods = new Array();
                        for ($i = 2; $i <= $xls_data->sheets[0]['numRows']; $i++)
                        {
                            $goods_onshelf_id = $xls_data->sheets[0]['cells'][$i][1];
                            $goods_onshelf = GoodsOnshelf::find("goods_onshelf_id = ?", $goods_onshelf_id)->getOne();
                            if (!$goods_onshelf->goods_id)
                            {
                                exit();
                            }
                            $goods_info = GoodsInfo::find("goods_id = ?", $goods_onshelf->goods_id)->getOne();
                            if (!$goods_info->property_id)
                            {
                                exit();
                            }
                            $goods_property = GoodsProperty::find("property_id = ?", $goods_info->property_id)->getOne();
                            
                            $json_goods[$i-2]["goods_onshelf_id"] = $goods_onshelf_id;
                            $json_goods[$i-2]["goods_name"] = $goods_info->goods_name;
                            $json_goods[$i-2]["goods_no"] = $goods_info->goods_name;
                            $json_goods[$i-2]["brand_name"] = $brand->brand_name;
                            $json_goods[$i-2]["detail"] = $goods_info->detail;
                            $json_goods[$i-2]["img_urls"] = $goods_info->img_urls;
                            $json_goods[$i-2]["weight"] = $goods_property->weight;
                            $json_goods[$i-2]["quantity"] = $goods_property->quantity;
                            $json_goods[$i-2]["unit"] = $goods_property->unit;
                            $json_goods[$i-2]["color"] = $goods_property->color;
                            $json_goods[$i-2]["model"] = $goods_property->model;
                            $json_goods[$i-2]["size"] = $goods_property->size;
                            $json_goods[$i-2]["stock"] = $goods_onshelf->stock;
                            $json_goods[$i-2]["mall_price"] = $goods_onshelf->mall_price;
                            $json_goods[$i-2]["vip_price"] = $goods_onshelf->vip_price;
                        }
                        $brand = Brand::find("brand_id = ?", $goods_info->brand_id)->getOne();
                        $json = new Array();
                        $json["goods_recommended"] = $json_goods;
                        $json_string = "fillAct(" . json_encode($json) . ", 'brand/brand_goods_recommended');";
                        $json_path = JSON_BRAND_RECOMMENDED_PATH . $brand->category_id . "/" . $goods_info->brand_id . "/";
                        if ($json_path != '.' && $json_path != '..' && !is_dir($json_path))
                        {
                            passthru("mkdir -p $json_path >/dev/null");
                        }
                        
                        $json_name = $json_path. $goods_info->brand_id . ".js";
                        $fh = fopen($json_name, "w");
                        if ( $fh == null )
                        {
                            //echo $callback .  "(" . $json . ")";
                            exit();
                        }
                        fwrite($fh, $json_string);
                        fclose($fh);
                    }
                }
            }
            catch (Exception $ex)
            {
                print_r($ex);
                exit();
            }
        }
    }
}